
###########################################################################
#  Copyright 2010 Jim Pulokas
#
#  This file is part of focusfun.
#  
#  focusfun is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  focusfun is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with focusfun.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################


import v4l2
from fcntl import ioctl
import os

class Focuser(object):
	def __init__(self, device):
		if isinstance(device, int):
			self.fd = device
		elif isinstance(device, file):
			self.fd = device.fileno()
		elif isinstance(device, str):
			self.fd = os.open(device, os.O_RDWR)
		else:
			raise ValueError('must be initialized with file name, file object, or file descriptor, not: %s' % (type(device),))
		self.ctrl = v4l2.v4l2_control()
		self.ctrl.id = v4l2.V4L2_CID_FOCUS_ABSOLUTE

	def get(self):
		ioctl(self.fd, v4l2.VIDIOC_G_CTRL, self.ctrl)
		return self.ctrl.value

	def set(self, value):
		self.ctrl.value = value
		ioctl(self.fd, v4l2.VIDIOC_S_CTRL, self.ctrl)
